//
//  HTkeyboardEmotionView.swift
//  表情键盘
//name:_currentPageImage,type:@"UIImage"
//name:_pageImage,type:@"UIImage"
//  Created by whtapple on 4/2/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit

class HTkeyboardEmotionView: UIView {
    let reuseIdentifier = "reuseIdentifier"
    //MARK: -属性
    weak var textView: UITextView?
    //MARK: -初始化
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 216))
        backgroundColor = UIColor.whiteColor()
        prepareUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    ///准备UI
    private func prepareUI(){
        //添加toolBarView到 view中
        addSubview(toolBarView)
        //添加collectionView到 view中
        addSubview(collectionView)
        //添加pageControl到 view中
        addSubview(pageControl)
        //开始时，选中的是第一个按钮，需要隐藏
        pageControl.hidden = true
        //注册 cell
        collectionView.registerClass(HTemotionKeyboardViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        //约束,取消resize
        toolBarView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        
        //vfl约束
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[vc]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["vc" : toolBarView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["tb":collectionView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ac]-0-[bc(37)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bc" : toolBarView,"ac":collectionView]))
        //pageControl约束
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
    }
    //重写layoutSubviews方法
    override func layoutSubviews() {
        super.layoutSubviews()
        (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = collectionView.frame.size
    }
    //MARK: - 懒加载
    //懒加载pagecontroll
    private lazy var pageControl: UIPageControl = {
        let pagecontrol = UIPageControl()
        pagecontrol.numberOfPages = 5
        pagecontrol.currentPage = 1
        //使用 KVC 添加隐藏属性，当然先拿到隐藏属性
        //        UIPageControl.printIvars()
        pagecontrol.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        //        pagecontrol.setValue(UIImage(named: "compose_keyboard_dot"), forKey: "_pageImage")
        pagecontrol.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        return pagecontrol
    }()
    //懒加载数据
    private lazy var toolBarView: HTToolBarView = {
        let toolbar = HTToolBarView.toolBar()
        toolbar.delegate = self
        return toolbar
    }()
    //懒加载数据
    private lazy var collectionView: UICollectionView = {
        //创建一个FlowLayout
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        //滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.bounces = false
        //分页滚动
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        //背景颜色图片
        //        collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_ba ckground")!)
        collectionView.dataSource = self
        collectionView.delegate = self
        return collectionView
    }()
}
//MARK: -cell代理方法
extension HTkeyboardEmotionView: emotionKeyboardViewCellDelegate{
    func emtionKeyboardViewCell(cell: HTemotionKeyboardViewCell, didSelectedModel model: HTEmotionModel) {
        HTEmotionModelManager.sharedManager.addfavorate(model)
               //守卫，看有没有textview
        guard let textview = textView else{
            assert(false, "textView不能为空")
            return
        }
        //如果是emoji表情，插入emoji表情
        if model.emoji != nil{
            textview.insertText(model.emoji!)
            return
        }
        //如果不是 emoji表情，就是图片表情
        if let fullpath = model.fullpngPath{
            //图片--附件--属性文本--属性文本可以加到 tableview
            //创建一个附件
            let attachment = HTEmotionAttachment()
            //给附件加上图片
            attachment.image = UIImage(named: fullpath)
            //给附件加一个名称
            attachment.chs = model.chs
            //算出文字高度
            let wh = textview.font?.lineHeight ?? 20
            //附件的 bounds根据文字高度
            attachment.bounds = CGRect(x: 0, y: -3, width: wh, height: wh)
            //将附件转化成属性文本
            let attr = NSAttributedString(attachment: attachment)
            //将属性文本转变为可变
            let attrM = NSMutableAttributedString(attributedString: attr)
            //添加属性
            attrM.addAttribute(NSFontAttributeName, value: textview.font!, range: NSRange(location: 0, length: 1))
            //不能直接替换文本，
            let oldAttr = NSMutableAttributedString(attributedString: textview.attributedText)
            let oldRange = textview.selectedRange
            oldAttr.replaceCharactersInRange(oldRange, withAttributedString: attrM)
            textview.attributedText = oldAttr
        }
    }
    //删除按钮回调
    func didClickDeleteButton() {
        self.textView?.deleteBackward()
    }
}
//MARK: -collectiongView代理拓展`
extension HTkeyboardEmotionView: UICollectionViewDelegate, UICollectionViewDataSource{
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HTEmotionModelManager.sharedManager.loadPackages().count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return HTEmotionModelManager.sharedManager.loadPackages()[section].pageemotions.count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HTemotionKeyboardViewCell
        //        cell.backgroundColor = UIColor.random()
        cell.emotionsModels = HTEmotionModelManager.sharedManager.loadPackages()[indexPath.section].pageemotions[indexPath.item]
        cell.delegate = self
        return cell
    }
    //MARK: -监听滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //    Xprint(msg: "\(scrollView.contentOffset)")
        //得到中心点
        var center = scrollView.center
        //拿到中心点在contentView中是否存在
        center.x += scrollView.contentOffset.x
        //判断在哪个 cell中
        for cell in collectionView.visibleCells(){
            if cell.frame.contains(center){
                let index = collectionView.indexPathForCell(cell)
                toolBarView.toolBarselectBtn(index!.section)
                //设置 pagecontrol
                setupPageControl(index!)
                
                break
            }
        }
    }
    //MARK: - 设置 pagecontrol
    private func setupPageControl(indexpath: NSIndexPath){
        //设置当前页
        pageControl.currentPage = indexpath.item
        //设置页数
        pageControl.numberOfPages = HTEmotionModelManager.sharedManager.loadPackages()[indexpath.section].pageemotions.count
        //当有0页时隐藏
        pageControl.hidden = indexpath.section == 0
    }
}
//MARK: -toolbar代理拓展
extension HTkeyboardEmotionView: HTToolBarViewDelegate {
    func toolBar(toolBar: HTToolBarView, selectedType: EmotiontoolBarButtonType) {
        let indexpath: NSIndexPath = NSIndexPath(forItem: 0, inSection: selectedType.rawValue)
        
        collectionView.selectItemAtIndexPath(indexpath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        //设置 pagecontrol
        setupPageControl(indexpath)
    }
}
